package com.origin.netlibrary


import com.origin.netlibrary.listener.DownloadListener
import com.origin.utils.log.LogUtils
import okhttp3.ResponseBody
import retrofit2.Response
import java.io.*

/**
 *
 */

class DownDone {


    companion object {

        private val downMap = mutableMapOf<String, Long>()

        public fun setPr(url: String, read: Long) {
            downMap[url] = read
        }

        public fun getPr(url: String): Long {
            return downMap[url] ?: 0
        }

        fun writeResponseToDisk(
            path: String,
            response: Response<ResponseBody>,
            downloadListener: DownloadListener, url: String
        ) {
            LogUtils._e("DownLoadService writeFileFromIS -1")
            //从response获取输入流以及总大小
            val body = response.body();
            LogUtils._e("DownLoadService writeFileFromIS -2")
            if (body == null) {
                downloadListener.onFail(response.toString(), url)
            } else {
                LogUtils._e("DownLoadService writeFileFromIS 0")
                body.apply {
                    LogUtils._e("DownLoadService writeFileFromIS 1")
                    writeFileFromIS(
                        File(path),
                        byteStream(),
                        contentLength(),
                        downloadListener, url
                    )
                }

            }


        }

        private const val sBufferSize = 8192



        //将输入流写入文件
        private fun writeFileFromIS(
            file: File,
            `is`: InputStream,
            totalLength: Long,
            downloadListener: DownloadListener, url: String
        ) {
            LogUtils._e("DownLoadService writeFileFromIS 2@")
            //开始下载
            downloadListener.onStart(url)

            //创建文件
            if (!file.exists()) {
                if (!file.parentFile.exists()) file.parentFile.mkdir()
                try {
                    file.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                    downloadListener.onFail("createNewFile IOException", url)
                }
            }
            var os: OutputStream? = null
            var currentLength: Long = 0
            val startTime = System.currentTimeMillis() // 开始下载时获取开始时间
            try {
                os = BufferedOutputStream(FileOutputStream(file,true))
                val data = ByteArray(sBufferSize)
                var len: Int
                while (`is`.read(data, 0, sBufferSize).also { len = it } != -1) {
                    os.write(data, 0, len)
                    val curTime = System.currentTimeMillis()
                    var usedTime = (curTime - startTime) / 1000
                    if (usedTime == 0L) {
                        usedTime = 1
                    }
                    currentLength += len.toLong()
                    //计算当前下载进度
                    val speed = currentLength / usedTime // 平均每秒下载速度
                    setPr(url, currentLength)
                    LogUtils._e("DownLoadService writeFileFromIS ${currentLength}")

                    downloadListener.onProgress(
                        (100 * currentLength / totalLength).toInt(),
                        Utils.setSize(speed),
                        url
                    )
                }
                //下载完成，并返回保存的文件路径
                downloadListener.onFinish(file.absolutePath, url)
            } catch (e: IOException) {
                e.printStackTrace()
                downloadListener.onFail("IOException", url)
            } finally {
                try {
                    `is`.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                try {
                    os?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }


}